<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_services_TreeService extends f_core_Service
{
	private $selectOptionsTab = Array();
	private static $instance;
	
	/**
	 * @return m_backoffice_services_TreeService
	 */
	private function __construct()
	{
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return m_backoffice_services_TreeService
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	public function getTree($nodeId, $lang)
	{
		$document = $this->getDocumentProvider()->getByUniqueId($nodeId, $lang);
		
		$documents = $this->getModuleListedDocuments($document->getDocumentModuleName());

		ob_start();
		echo '<ul id="tree"><li><span>{icon name="'.$document->getIcon().'"} '.$document->getLabel().'</span>';
		$this->getRecursiveNodes($document, $documents, $lang);
		echo '</li></ul>';
		$table = ob_get_clean();
		return $table;
	}
	
	private function getRecursiveNodes($node, $authorizedDocs, $lang)
	{
		$relManager = f_relation_ManagerNew::getInstance($node);

		$childs = $relManager->getChilds()->withModel($authorizedDocs)->withlang($lang)->retrieveDocuments();
		
		$hasChilds = count($node->relationFields()) > 0;
		if($hasChilds)
		{
			echo "\n".'<ul>'."\n";
			echo "<li class=\"sortable-node unmovable\">&nbsp</li>";
		}
		
		foreach($childs as $child)
		{
			if(count($child->relationFields()) > 0)
			{
				echo "\n"."<li class=\"sortable-node\"><span>{icon name='".$child->getIcon()."'} ".$child->getLabel()."</span>";
			}
			else
			{
				echo "\n"."<li class=\"sortable-node\"><span>{icon name='".$child->getIcon()."'} ".$child->getLabel()."</span>";
			}
			
			if(count($child->relationFields()) > 0)
			{
				$this->getRecursiveNodes($child, $authorizedDocs, $lang);
			}	
			
			echo "</li>"."\n";				
		}
		
		if($hasChilds)
		{
			echo "\n".'</ul>';
		}
	}
	
	private function getModuleListedDocuments($moduleName)
	{
		$treeFile = m_backoffice_services_MenuService::getInstance()->parseModuleTreefile($moduleName);
		return $treeFile->getAuthorizedDocTypes();
	}

    /**
     * Function to make hierarchical select <select><option value=tab[0] selected=tab2>tab1</option>
     * @param <type> $rootModule
     * @param <type> $documentModel
     * @param <type> $selectedId
     * @param <type> $isRoot = put the root document in the array
     * @param <type> $recursive
     * @param <type> $foldersModule = put the module name
     * @param <type> $rights = put the rights that must be taken into account
     * @return <type> Array to make hierarchical select
     *
     * @deprecated use m_backoffice_service_SelectService instead !
     */
	public function getSelectArray($rootModule, $documentModel, $selectedId = null, $showRoot = false, $recursive = true, $foldersModule = null, $rights = null)
	{
        $this->selectOptionsTab = array();

        $docProvider = $this->getDocumentProvider();

        $doc = $docProvider->checkDocument($rootModule) ? $docProvider->getByUniqueId($rootModule) : m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode($rootModule);

        if(is_object($doc))
        {
            $docId = $doc->getUniqueId();
        }
        else
        {
            return null;
        }

		$options = $docId == $selectedId ? 'selected="selected"' : "";

		$subGroup = $this->getChildDocuments($docId, $documentModel, $selectedId, $recursive, $foldersModule, $rights);


        if($showRoot)
        {
            $root[] = $docId;
            $root[] = $doc->getModel() == 'modules_backoffice/rootNode' ? '/' : $doc->getLabel();
            $root[] = '';
            $root[] = true;
            $res = array($root);
            $res[] = $subGroup;
            $subGroup = $res;
        }

		$this->readChildDocuments($subGroup, 0);

		return $this->selectOptionsTab;
	}

	/*
	 * Get the child document from and Id.
	 * @return array
	 */
    private $valid = true;
	private function getChildDocuments($docId, $documentModel, $selectedId = null, $recursive = true, $foldersModule = null, $rights = null)
	{
		$documentProvider = f_document_Provider::getInstance();
		$groupsData = f_relation_Manager::getInstance()->getChildsByDocType($docId, $documentModel, null, array("relation_order" => "ASC"));
        $subGroupData = array();

		foreach ($groupsData as $data)
		{
            if(!is_null($foldersModule) && $data->getModel() == 'modules_backoffice/folder')
            {
                if($data->getModule() != $foldersModule)
                {
                    continue;
                }
            }
            
            $authorization = true;
            if(!is_null($rights))
            {
                $authorization = $this->getUser()->hasDocRight($data, $data->getModule(), $rights) ? true : false;
            }

            $options = "";
            if($authorization == true)
            {
                if(!is_null($selectedId))
                {
                    $options = $data->getUniqueId() == $selectedId ? 'selected="selected"' : "";
                }
                else
                {
                    if($this->valid == true)
                    {
                        $this->valid = false;
                        $options = 'selected="selected"';
                    }
                }
            }

            $subGroupData[] = array($data->getUniqueId(), $data->getLabel(), $options, $authorization);

            if($recursive)
            {
                $subGroup = $this->getChildDocuments($data->getUniqueId(), $documentModel, $selectedId, $recursive, $foldersModule, $rights);

                if(!empty($subGroup))
                {
                    $subGroup[] = $authorization;
                    $subGroupData[] = $subGroup;
                }
            }
		}

		return $subGroupData;
	}

	private function readChildDocuments($subGroup, $level = 0, $folderModule = null)
	{
		$i = 1;
        if(!empty($subGroup))
        {
            foreach($subGroup as $data)
            {
                if(!empty($data))
                {
                    if(isset($data[0]) && is_array($data[0]) && !empty($data[0]))
                    {
                        $level2 = $level + 0.9;
                        $this->readChildDocuments($data, $level2);
                    }
                    else
                    {
                        $arbo = '';
                        if($level > 0)
                        {
                            $arbo = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level);
                            $nb = count($subGroup);
                            $arbo .= $nb == $i ? "└ " : "├ ";
                        }

                        $this->selectOptionsTab[] = array($data[0], $arbo . $data[1], $data[2], $data[3]);
                    }
                }

                $i++;
            }
        }
	}
}